package com.youdoneed.common.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.youdoneed.base.application.StringDateParser;
import com.youdoneed.base.common.GsonUtils;

import java.util.Date;

public class AliOssSTS {
    private static final String STS_API_VERSION = "2015-04-01";
    // 目前只有"cn-hangzhou"这个region可用, 不要使用填写其他region的值
    private static final String REGION_CN_HANGZHOU = "cn-hangzhou";
    // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
    private static IClientProfile profile = DefaultProfile.getProfile(
            REGION_CN_HANGZHOU, Config.accessKeyId, Config.accessKeySecret);
    private static DefaultAcsClient client = new DefaultAcsClient(profile);

    private AliOssSTS() {
    }

    /**
     * 配置信息。
     */
    private static class Config {
        public static String accessKeyId = "LTAI4XApLcd4O5j0";
        public static String accessKeySecret = "pZLJyKypyxhp2ZgA61Jv6ya6kkXiVJ";
        public static String roleArn = "acs:ram::1240620114327010:role/aliyunosstokengeneratorrole";
        public static long tokenExpireTime = 3600;
        public static String policy = GsonUtils.toJson(new Policy());
    }

    /**
     * 权限控制策略。
     */
    private static class Policy {
        public Statement[] Statement = {new Statement()};
        public String Version = "1";
    }

    /**
     * 权限描述。
     */
    private static class Statement {
        public String[] Action = {"oss:PutObject",
                "oss:GetObject",
                "oss:ListObjects"};
        public String Effect = "Allow";
        public String[] Resource = {"acs:oss:*:*:youdoneed-test/*",
                "acs:oss:*:*:youdoneed-test"};
    }

    public static class STSResult {
        public String Status;
        public String Message;
        public String AccessKeyId;
        public String AccessKeySecret;
        public String SecurityToken;
        public Date Expiration;
    }

    public static STSResult assumeSTSToken(String roleSessionName) {
        STSResult result = new STSResult();
        try {
            // 创建一个 AssumeRoleRequest 并设置请求参数
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setVersion(STS_API_VERSION);
            request.setMethod(MethodType.POST);
            request.setProtocol(ProtocolType.HTTPS);
            request.setRoleArn(Config.roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(Config.policy);
            request.setDurationSeconds(Config.tokenExpireTime);
            // 发起请求，并得到response
            AssumeRoleResponse stsResponse = client.getAcsResponse(request);
            result.Status = "200";
            result.Message = "Success";
            result.AccessKeyId = stsResponse.getCredentials().getAccessKeyId();
            result.AccessKeySecret = stsResponse.getCredentials().getAccessKeySecret();
            result.SecurityToken = stsResponse.getCredentials().getSecurityToken();
            // 阿里返回的是UTC时间（0时区）
            result.Expiration = StringDateParser.stringToDate(
                    stsResponse.getCredentials().getExpiration());
        } catch (ClientException e) {
            result.Status = e.getErrCode();
            result.Message = e.getMessage();
        }
        return result;
    }

}
